package com.hirsi.core.expand;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ClassUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 封夕
 * @since 2023/3/7 15:39
 */
public interface TableRUpdate {

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Result<T> {

        private List<T> saves;

        private List<Integer> deleteIds;
    }


    static <E extends TableRUpdate> Result<E> execute(List<E> submitList, List<E> oldList) {
        List<E> copySubmitList = new ArrayList<>();
        List<E> copyOldList = new ArrayList<>();
        //深拷贝，不影响原数据
        if (CollUtil.isNotEmpty(submitList)) copySubmitList = BeanUtil.copyToList(submitList, ClassUtil.getClass(submitList.get(0)));
        if (CollUtil.isNotEmpty(oldList)) copyOldList = BeanUtil.copyToList(oldList, ClassUtil.getClass(oldList.get(0)));
        //历史集合在新集合中不存在的数据
        List<E> finalCopySubmitList = copySubmitList;
        List<E> tempList = copyOldList.stream().filter(old -> finalCopySubmitList.stream().map(E::getEqualsField).noneMatch(r -> r.equals(old.getEqualsField()))).collect(Collectors.toList());
        //这是新增的
        List<E> finalCopyOldList = copyOldList;
        List<E> newList = copySubmitList.stream().filter(submit -> finalCopyOldList.stream().map(E::getEqualsField).noneMatch(r -> r.equals(submit.getEqualsField()))).collect(Collectors.toList());
        //这是交集
        List<E> updateList = copyOldList.stream().filter(old -> finalCopySubmitList.stream().map(E::getEqualsField).anyMatch(r -> r.equals(old.getEqualsField()))).collect(Collectors.toList());
        List<E> insertList = null;
        //提取出要删除的id
        List<Object> deleteIds = null;
        //判断：如果新增的数量大于历史的数量，截取新增的多出来的
        if (newList.size() > tempList.size()) {
            insertList = newList.subList(tempList.size(), newList.size());
        } else {
            //如果新增的数量小于历史的数据，则截取历史数据多出来的历史数据的id，后边进行删除
            deleteIds = tempList.stream().skip(newList.size()).map(E::getId).collect(Collectors.toList());
            //这里截取为和newList数量相等的
            tempList = tempList.subList(0, newList.size());
        }
        for (int i = 0; i < tempList.size(); i++) {
            //把历史的数据的rid都更新为新增的rid
            tempList.get(i).setEqualsField(newList.get(i).getEqualsField());
        }
        //如果新增有多出来的，则加进去
        if (insertList != null) tempList.addAll(insertList);

        return new Result(tempList, deleteIds);
    }

    @JsonIgnore
    Object getEqualsField();

    void setEqualsField(Object equalsField);

    @JsonIgnore
    Object getId();

}
